package cc.lucien.Controller;

import cc.lucien.entity.Course;
import cc.lucien.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author lucien-ma
 * @date 2021/9/7
 * @apiNote RESTful 案例练习，Controller 代码
 */
@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseRepository courseRepository;

    @GetMapping("/findAll")
    public ModelAndView findAll() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("courseIndex");
        modelAndView.addObject("list", courseRepository.findAll());
        return modelAndView;
    }

    @PostMapping("/save")
    public String save(Course course) {
        courseRepository.saveOrUpdate(course);
        return "redirect:/course/findAll";
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id") Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("edit");
        modelAndView.addObject("course", courseRepository.findById(id));
        return modelAndView;
    }

    @PutMapping("/update")
    public String update(Course course) {
        courseRepository.saveOrUpdate(course);
        return "redirect:/course/findAll";
    }

    @DeleteMapping("/delete/{id}")
    public String deleteById(@PathVariable("id") Integer id) {
        courseRepository.deleteById(id);
        return "redirect:/course/findAll";
    }
}
